<?php
declare(strict_types=1);

namespace App;

class Config
{
    protected readonly App $app;

    protected array $config = [];

    public function __construct(App $app)
    {
        $this->app = $app;
        $this->loadConfig();
    }

    public function loadConfig(): void
    {
        $configs = glob(BASE_PATH . '/config/*.php');
        array_walk($configs, function ($config) {
            $this->config = array_merge($this->config, [basename($config, '.php') => require $config]);
        });
    }

    /**
     * @param string $key
     * @param mixed|null $default
     * @return mixed
     */
    public function get(string $key, mixed $default = null): mixed
    {
        $keys = explode('.', $key);
        $config = $this->config;
        foreach ($keys as $k) {
            if (!isset($config[$k])) {
                return $default;
            }
            $config = $config[$key];
        }
        return $config;
    }

}